package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Long userId, Long friendId) {
        //1. 先判断userId和friendId是否已经是好友,如果不是,再添加
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);
        if (friend1 == null) {
            friend1 = new Friend();
            friend1.setFriendId(friendId);
            friend1.setUserId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        //2. 先判断friendId和userId是否已经是好友,如果不是,再添加
        Query query2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        if (friend2 == null) {
            friend2 = new Friend();
            friend2.setFriendId(userId);
            friend2.setUserId(friendId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public PageBeanVo findFriendByUserId(Long userId, Integer pageNum, Integer pageSize) {
        //条件
        Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);

        //查询
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        //统计
        long count = mongoTemplate.count(query, Friend.class);

        return new PageBeanVo(pageNum, pageSize, count, friendList);
    }

    @Override
    public void delete(Long userId, Long likeUserId) {
        //1. 删除我--它
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        mongoTemplate.remove(query1, Friend.class);

        //2. 删除它--我
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("friendId").is(userId));
        mongoTemplate.remove(query2, Friend.class);
    }
}
